package bookTrading.seller;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import java.math.BigDecimal;
import java.text.DecimalFormat;

@SuppressWarnings("serial")
public class SellerPropose extends CyclicBehaviour
{
	public static Double valorAnterior;
	private AgentSeller agentSeller;


	// Construtor
	public SellerPropose(AgentSeller agentSeller)
	{
		this.agentSeller = agentSeller;
	}


	@Override
	public void action()
	{
		MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.PROPOSE);
		ACLMessage msg = agentSeller.receive(mt);

		if (msg != null)
		{
			Double valorProposto = Double.parseDouble(msg.getContent());
			
			DecimalFormat df = new DecimalFormat("#,###.00");
			System.out.println("[Propose] Comprador ofereceu: R$ " + df.format(valorProposto));
			
			ACLMessage reply = msg.createReply();
			
			valorAnterior -= valorAnterior / 10; // Subtrai -10%
			
			BigDecimal b = new BigDecimal(valorAnterior);
			valorAnterior = Double.parseDouble(String.valueOf(b.setScale(2, BigDecimal.ROUND_DOWN)));

			if (valorProposto >= valorAnterior)
			{
				reply.setPerformative(ACLMessage.ACCEPT_PROPOSAL);
				reply.setContent(String.valueOf(valorAnterior));
			}
			else
			{
				reply.setPerformative(ACLMessage.PROPOSE);
				reply.setContent(String.valueOf(valorAnterior));
			}
			
			agentSeller.send(reply);
		}
		else
			block();
	}
}